/*
 * Copyright (C) 2025 Thomas Akehurst
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.tomakehurst.wiremock.db.utils;

import com.github.tomakehurst.wiremock.core.DatabaseMappingsSourceProvider;
import com.github.tomakehurst.wiremock.standalone.MappingsSource;

import javax.sql.DataSource;

/**
 * @description:
 * @author: 17536
 * @time: 2025/8/11 10:36
 */
/**
 * 数据库映射源提供者：支持固定配置 + 动态数据源
 */
public class MyBatisMappingsSourceProvider implements DatabaseMappingsSourceProvider {
  // 新增：动态数据源（若外部注入则使用，否则用XML配置）
  private DataSource dynamicDataSource;

  /**
   * 默认构造：使用 mybatis-config.xml 中的数据源（原有逻辑）
   */
  public MyBatisMappingsSourceProvider() {}

  /**
   * 新增：带数据源的构造（供外部注入动态数据源，如Spring环境）
   */
  public MyBatisMappingsSourceProvider(DataSource dataSource) {
    this.dynamicDataSource = dataSource;
  }

  /**
   * 核心方法：获取 MappingsSource
   * 优化：优先使用动态数据源，无则用XML配置
   */
  @Override
  public MappingsSource getMappingsSource() {
    if (dynamicDataSource != null) {
      // 使用动态数据源（如WireMock配置中注入的数据源）
      return MyBatisUtil.getDatabaseMappingsSource(dynamicDataSource);
    } else {
      // 兼容原有逻辑：使用XML配置的数据源
      return MyBatisUtil.getDatabaseMappingsSource();
    }
  }

  /**
   * 新增：注入动态数据源（供外部配置调用）
   */
  public void setDynamicDataSource(DataSource dynamicDataSource) {
    this.dynamicDataSource = dynamicDataSource;
  }
}
